package com.daocao.hua.info;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.daocao.hua.http.InfoCallBack;
import com.daocao.hua.util.CheckContainChinese;
import com.daocao.hua.util.FilterStr;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通话记录
 * Created by MasterDong on 16/9/8.
 */
public class PhoneContacts {

    /**
     * 获取库Phone表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};

    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;

    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;

    private Context context;
    private List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    private List<Map<String, String>> newList = new ArrayList<Map<String, String>>();


    public PhoneContacts(Context context) {
        this.context = context;
    }


    /**
     * 得到手机通讯录联系人信息
     **/
    private void getPhoneContacts() {
        try {
            ContentResolver resolver = context.getContentResolver();

            // 获取手机联系人
            Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);


            if (phoneCursor != null) {
                while (phoneCursor.moveToNext()) {

                    //得到手机号码
                    String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                    //当手机号码为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(phoneNumber)) continue;

                    //得到联系人名称
                    String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                    // 当姓名为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(contactName)) continue;

                    String newName = URLEncoder.encode(FilterStr.filter(contactName), "utf-8");
                    String newPhone = FilterStr.filterNumber(phoneNumber);

                    Map<String, String> map = new HashMap<String, String>();
                    if (CheckContainChinese.checkStringContainChinese(newName))
                        map.put("full_name", URLEncoder.encode(newName, "utf-8"));
                    else
                        map.put("full_name", newName);

                    if (CheckContainChinese.checkStringContainChinese(newPhone))
                        map.put("phone", URLEncoder.encode(newPhone, "utf-8"));
                    else
                        map.put("phone", newPhone);

                    list.add(map);

                }
                if (phoneCursor != null)
                    phoneCursor.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    /**
     * 得到手机SIM卡联系人人信息
     **/
    private void getSIMContacts(String adn) {
        try {
            ContentResolver resolver = context.getContentResolver();
            // 获取Sims卡联系人
            Intent intent = new Intent();
            intent.setData(Uri.parse(adn));
            Uri uri = intent.getData();

            Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
                    null);

            if (phoneCursor != null) {
                while (phoneCursor.moveToNext()) {

                    // 得到手机号码
                    String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                    // 当手机号码为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(phoneNumber)) continue;

                    // 得到联系人名称
                    String contactName = phoneCursor
                            .getString(PHONES_DISPLAY_NAME_INDEX);
                    // 当姓名为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(contactName)) continue;

                    String newName = URLEncoder.encode(FilterStr.filter(contactName), "utf-8");
                    String newPhone = FilterStr.filterNumber(phoneNumber);

                    Map<String, String> map = new HashMap<String, String>();
                    if (CheckContainChinese.checkStringContainChinese(newName))
                        map.put("full_name", URLEncoder.encode(newName, "utf-8"));
                    else
                        map.put("full_name", newName);

                    if (CheckContainChinese.checkStringContainChinese(newPhone))
                        map.put("phone", URLEncoder.encode(newPhone, "utf-8"));
                    else
                        map.put("phone", newPhone);

                    list.add(map);
                }

                if (phoneCursor != null)
                    phoneCursor.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 合并相同的Map
     *
     * @param list
     * @return
     */
    public List<Map<String, String>> mergeList(List<Map<String, String>> list) {
        List<Map<String, String>> newList = list;
        try {
            for (int i = 0; i < list.size(); i++) {
                Map<String, String> map = list.get(i);
                String name = null, phone = null;
                if (!TextUtils.isEmpty(map.get("full_name")))
                    name = map.get("full_name").toLowerCase();
                if (!TextUtils.isEmpty(map.get("phone")))
                    phone = map.get("phone").replaceAll(" ", ""); //去掉空格

                for (int j = i + 1; j < list.size(); j++) {
                    Map<String, String> innerMap = list.get(j);
                    String name1 = null, phone1 = null;
                    if (!TextUtils.isEmpty(map.get("full_name")))
                        name1 = innerMap.get("full_name").toLowerCase();
                    if (!TextUtils.isEmpty(map.get("phone")))
                        phone1 = innerMap.get("phone").replaceAll(" ", "");  //去掉空格

                    if (name.equals(name1) && phone.equals(phone1))
                        newList.remove(j);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newList;
    }


    /**
     * 获取通讯录
     */
    public void getContacts(final InfoCallBack callBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                list.clear();
                getPhoneContacts();
                getSIMContacts("content://icc/adn");
                getSIMContacts("content://sim/adn");
                newList = mergeList(list);
//                RBLog.i("listSize:------- ", newList.size());

                new Handler(context.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (newList.size() > 0)
                            callBack.onSuccess(newList);
                        else
                            callBack.onFailure("");
                    }
                });

            }
        }).start();
//        return newList;
    }

}
